<?php !defined( 'SUNCMS' ) && exit( 'No direct script access allowed'  );

/**
 * 
 * Sun CMS
 * 
 * @author			Burning
 * @copyright		Copyright (c) 2009, IsunCms.Com.
 * @license			http://www.isuncms.com/license.htm
 * @link				http://www.isuncms.com/
 * @since				Version 1.0 Beta
 * 
 */

class Times
{
	var $db;
	var $table;
	var $action;
	var $starttime;
	var $times;
    
    function __construct()
    {
		global $db;
		$this->db = $db;
		$this->table = DB_PRE.'times';
    }

	function set( $action, $interval = 3600, $times = 1 )
	{
		$this->action = $action;
		$this->starttime = TIME - max( intval($interval), 1 );
		$this->times = max( intval($times), 1 );
	}

	function get()
	{
		$sql = "SELECT `time`,`times` FROM `$this->table` WHERE `action`='$this->action' AND `ip`='".IP."'";
		return $this->db->query( $sql, true );
	}

	function add()
	{
		$sql = "SELECT `time`,`times` FROM `$this->table` WHERE `action`='$this->action' AND `ip`='".IP."'";
		$result = $this->db->query( $sql, true );
		if( $result )
		{
			$times = $result['time'] < $this->starttime ? 1 : "`times`+1";
			$update = "UPDATE `$this->table` SET `time`='".TIME."', `times`=$times WHERE `action`='$this->action' AND `ip`='".IP."'";
			$this->db->execute( $update );
		}
		else
		{
			$this->db->insert( $this->table, array( 'action' => $this->action, 'ip' => IP, 'time' => TIME, 'times' => 1 ) );
		}
	}

	function check()
	{
		$sql = "SELECT `time`,`times` FROM `$this->table` WHERE `action`='$this->action' AND `ip`='".IP."' AND `time`>=$this->starttime AND `times`>=$this->times";
		return $this->db->query( $sql, true );
	}

	function clear()
	{
		$sql = "DELETE FROM `$this->table` WHERE `action`='$this->action' AND (`ip`='".IP."' OR `time` < $this->starttime)";
		return $this->db->execute( $sql );
	}
}